package StudyCode.summary.zipfile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

/**
 * 版权所有 科技与人文(www.tah1986.com)
 */
public class UnzipToDir {
	public static void unzipToDir(Path dir, String resourcePath)
			throws IOException {
//		InputStream repoZipStream = ZipUtils.class.getResourceAsStream(resourcePath);
//		ZipInputStream zipStream = new ZipInputStream(repoZipStream);
//
//		ZipEntry entry;
//		while ((entry = zipStream.getNextEntry()) != null) {
//			if (!entry.isDirectory()) {
//				unzipFile(dir, entry, zipStream);
//			}
//		}
	}

	private static void unzipFile(Path targetDir, ZipEntry entry,
	                              ZipInputStream stream) throws IOException {
		String name = entry.getName();
		File outFile = new File(targetDir.toFile(), name);
		Path parent = outFile.toPath().getParent();
		if (!Files.exists(parent) && !parent.toFile().mkdirs()) {
			throw new IllegalStateException("不能创建目录: "
					+ parent);
		}
		byte[] buffer = new byte[10000];
		if (!outFile.createNewFile()) {
			throw new IllegalStateException("不能创建文件: "
					+ outFile);
		}
		int read;
		try (FileOutputStream outputStream = new FileOutputStream(outFile)) {
			while ((read = stream.read(buffer)) >= 0) {
				outputStream.write(buffer, 0, read);
			}
		}
	}
}
